import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import { longmao } from '@/utils/sso'

let dev = /^dev.+$/.test(window.document.domain) ? 'dev.' : ''
let offline = /^offline.+$/.test(window.document.domain) ? 'offline.' : ''
let prefix = offline != '' ? offline : dev
let SERVER_HOST = 'http://128.196.150.85:1350' // api 的 base_url


const service = axios.create({
    baseURL: SERVER_HOST
})

service.interceptors.request.use(
    config => {
        if (getToken()) {
            config.headers['Token'] = getToken()
        }
        return config;
    },
    error => {
        console.log(error)
        Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        if (response.data.code == '200') {
            if (response.data) {
                return response.data
            } else {
                return response.data
            }
        } else if (response.data.code == '401') {
            Message({
                message: '登录超时',
                duration: 1500,
                type: 'error'
            })
            setTimeout(() => {
                longmao.sso.login();
            }, 1000);
        } else {
            let message
            if (response.data.message && response.data.message.length) {
                message = response.data.message
            } else {
                message = '服务异常'
            }
            Message({
                message: message,
                duration: 1500,
                type: 'error'
            })
            return new Error(response.data.message)
        }

    },
    error => {
        // console.log('err' + error) // for debug
        Message({
            message: '请求超时，请检查网络状况',
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service;